package com.ThreadSyncEg;

import java.util.concurrent.locks.ReentrantLock;
//lock接口类 锁
// ReentrantLock 可重入锁
public class TestLock {
    public static void main(String[] args) {
        LockObj lockObj = new LockObj();
        new Thread(lockObj,"B").start();
        new Thread(lockObj,"A").start();
        new Thread(lockObj,"C").start();
    }

}
class LockObj implements Runnable{

    int tickets = 50;
    //可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            lock.lock(); //一般不将锁的获取放在try语句块中，因为如果发生异常，在抛出异常的同时，也会导致锁的无故释放
            try {
                //加锁
                if(tickets>0){
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"是"+tickets--);
                }else{
                    break;
                }
            } finally {
                //解锁 finally保证锁一定会被释放
                lock.unlock();
            }
        }
    }
}
